<?php
include_once (S_ROOT . './source/function_user.php');
include_once (S_ROOT . './source/api_class.php');

class Data {
    public $id;
    public $uid;
    public $type;
    public $tpls;
    public $list_name;
    public $apis;
    public $start  = 0;
    public $length = 100;
    
    public function __construct($uid, $type, $id) {
        $this->id    = $id;
        $this->uid   = $uid;
        $this->type  = $type;
        $this->tpls       = array('emotion' => '表情', 'paper' => '信纸', 'font' => '字体', 'skin' => '皮肤', 'proemotion' => '表情VIP', 'propaper' => '信纸VIP');
        $this->list_name  = array('emotions', 'papers', 'fonts', 'skins');
        $this->apis       = array(
                                'list'      =>  array('getEmotionList', 'getPaperList', 'getFontList', 'getSkinList', 'getProEmotionList', 'getProPaperList'),
                                'detail'    =>  array('getEmotionDetail', 'getPaperDetail', 'getFontDetail', 'getSkinDetail'),
                                'add'       =>  array('addEmotion', 'addPaper', 'addFont', 'addSkin'),
                                'edit'      =>  array('editEmotion', 'editPaper', 'editFont', 'editSkin'),
                                'buy'       =>  array('buyEmotion', 'buyPaper', 'buyFont', 'buySkin'),
        );
        $this->packType  = array('getPaperList'=>0,'getEmotionList'=>1);
    }
    
    public function execute ($action) {
      
        $do = $this->getDo ($action);
        return $this->$do($action);
    }
    
    /**
     * 获取商品列表
     * @param unknown $action
     * @return string
     */
    public function getShopList ($action) {
      
        $result   = $this->shopListRequest($action);
//         echo '<pre>';
//         print_r($result);exit;
        $list     = $this->resultListData($result);
   
        // 通用变量
        $data = $this->styleVariable($action);
       
        $data['list'] = $list;
        $data['packtype']=  $this->packType[$action];
        // 模板渲染到'shop_list.html'页面,用到的变量为render第二个参数中的数据
	
        return $this->render('shop', $data);
    }
    
    /**
     * 获取商品详情
     * @param unknown $action
     * @return string
     */
    public function getShopDetail ($action) {
        // 请求表情详情数据
        $result   = $this->shopDetailRequest($action);
      
        $detail   = $this->goodsDetailData($result);
       
        // 通用变量
        $data = $this->styleVariable($action);
        $data['detail'] = $detail;
     	
        // 模板渲染到'shop_detail.html'页面,用到的变量为render第二个参数中的数据
        return $this->render('shop_detail', $data);
    }
    
    // 编辑商品
    public function editShop ($action) {
        // 请求表情详情数据
      
        $result   = $this->shopEditRequest($action);
        $shopName=substr($action, 4);
        
        if ($result) {           
            showmessage('修改成功','admin.php?ac=shop&op=get'.$shopName.'List');
            exit;
        }
        showmessage('修改失败','admin.php?ac=shop&op=get'.$shopName.'Detail&id='.$_GET['id']);
        exit;
    }
    
    public function addShop ($action) {
        // 请求表情详情数据

        $result   = $this->shopAddRequest($action);    
       
           if($result){
                    echo 1;
                    exit;
                }
                echo 0;
                 exit;
    
    }
    
    // 请求服务器商店列表数据
    private function shopListRequest ($action) {
        // 组装请求服务器的数据
        $param = array(
            'do'        =>  'shop',
            'format'    =>  'json',
            'action'    =>  $action,
            'uid'       =>  $this->uid,
            'type'      =>  $this->type,
            'id'        =>  $this->id,
            'start'     =>  $this->start,
            'length'    =>  $this->length
        );
        
        return $this->requestApi($action, $param);
    }
    
    // 请求服务器商品详情数据
    private function shopDetailRequest ($action) {
        $param = array(
            'do'        =>  'shop',
            'format'    =>   'json',
            'action'    =>  $action,
            'uid'       =>  $this->uid,
            'id'        =>  $this->id
        );
        
        return $this->requestApi($action, $param);
    }
    
    // 请求服务器编辑商品
    private function shopEditRequest ($action) {
        $param = $this->goodsEditOrAddData($action);
     
        return $this->requestApi($action, $param);
    }
    
    // 请求服务器添加商品
    private function shopAddRequest ($action) {
        $param = $this->goodsEditOrAddData($action);
        
        return $this->requestApi($action, $param);
    }
    
    private function goodsEditOrAddData ($action) {
        $info = array(
             'id'             =>    empty($_GET['id'])? 0 : intval($_GET['id']),
            'name'            =>    empty($_GET['name'])? '' :strval($_GET['name']),  
            'status'          =>    isset($_GET['status'])? intval($_GET['status']): 1,
            'label'           =>    empty($_GET['label'])? 0 :intval($_GET['label']),
            'vip'             =>    empty($_GET['vip'])? 0 :intval($_GET['vip']),
            'name_tag'        =>    empty($_GET['name_tag'])? 0 :intval($_GET['name_tag']),
            'tag'             =>    empty($_GET['tag'])? 'new' :strval($_GET['tag']),
            'zip_size'        =>    empty($_GET['zip_size'])? 1024 :intval($_GET['zip_size']),
            'zip_url'         =>    empty($_GET['download_url'])? '' :strval($_GET['download_url']),
            'sale_amount'     =>    empty($_GET['sale_amount'])? 0 :intval($_GET['sale_amount']),
            'price_orign'     =>    empty($_GET['price_orign'])? 0 :intval($_GET['price_orign']),
            'price_final'     =>    empty($_GET['price_final'])? 0 :intval($_GET['price_final']),
            'cuid'            =>    empty($_GET['cuid'])? 3 :intval($_GET['cuid']),
            'desc'            =>    empty($_GET['desc'])? '':strval($_GET['desc']),
            'cover'           =>    empty($_GET['cover'])? 'static/img/default_sz.jpg':strval($_GET['cover']),
            'cover_s'         =>    empty($_GET['cover'])? 'static/img/default_sz.jpg':strval($_GET['cover']),
            'background'      =>    empty($_GET['background'])? '':strval($_GET['background']),
        	'extra'			  =>	'',
            'thumbnail'       =>    $this->thumbailImportData($action, $_GET['thumbnail_m'], $_GET['thumbnail_s']),
            'task'            =>    $this->taskImportData(),
            'action'          =>    $action,
        	'do'       		  =>   'shop',
        	'format'    	  =>   'json',          
        );
        
        return $info;
    }
    
    // 商品详情数据
    private function goodsDetailData ($result) {
        if (empty($result)) return array();
      
        // 通用显示
        $key_arr = array('id', 'name', 'desc', 'cover', 'background', 'expire_time', 'vip',
            'dateline','zip_size', 'sale_amount','price_orign', 'price_final', 'download_url'
        );
        $data = $this->assembleReplacedFieldData($result, $key_arr);
      
        // 状态显示
        $status     = $result['status'];
        $status_css = $this->cssShowSelected($status);

        // 资源样式显示
        $name_tag     = $result['name_tag']['bg'];
        $name_tag_css = $this->cssShowSelected($name_tag);
        
        // vip样式显示
        $vip     = $result['vip'];
        $vip_css = $this->cssShowSelected($vip);
        
        // 标签显示
        $tag     = $result['tag'][0]['bg'];
        $tag_css = array();
        if (!empty($tag)) {
            $tag_css = $this->cssShowSelected($tag);
        }
        
        // 任务
        $task = '';
       
        if (!empty($result['task'])) {
            //$task = implode('|', array_slice($result['task'], 0, 3));
            $task_type=$result['task']['type'];
            $task_num =$result['task']['num'];
            $task_msg =$result['task']['desc'];
        }
        
        
        // 预览图显示(根据不同)
        $thumbnail = $this->thumbailExportData($result['download_url'], $result['thumbnail']);
         
        // 商品作者
        $author_uid = $result['author']['uid'];
        
        $data['status_css']     = $status_css;
        $data['name_tag_css']   = $name_tag_css;
        $data['vip_css']        = $vip_css;
        $data['tag_css']        = $tag_css;
        $data['task_type']      = $task_type;
        $data['task_num']       = $task_num;
        $data['task_msg']       = $task_msg;
        $data['thumbnail']      = $thumbnail;
        $data['cuid']           = $author_uid;
        
        return $data;
    }
    
    // 组装预览图的显示数据
    private function thumbailExportData ($download_url, $thumbnail) {
    	
    	if(empty($download_url)) return array('m' => '', 's' => '');
        $goods_info = $this->parseDownLoadUrl($download_url);
      
        $thumbnail_s = $thumbnail_m = array();
        switch ($goods_info['type']) {
            case 'paper':
                $baseUrl = "http://d.fenfenriji.com/diary/paper/".$goods_info['id']."/priview/";
                $url = array();
                $thumbnails = explode(',', $thumbnail);
             
                foreach($thumbnails as $value){
                    $url[] = mb_substr($value,strlen($baseUrl));
                }              
                $thumbnail_s = $thumbnail_m = implode(',',$url);
                break;
            case 'emotion':
                $baseUrl_s = "http://d.fenfenriji.com/diary/emotion/".$goods_info['id']."/priview/".$goods_info['name']."_";
                $baseUrl_m = "http://d.fenfenriji.com/diary/emotion/".$goods_info['id']."/".$goods_info['name']."/".$goods_info['name']."_";
            
                // 处理预览图
                foreach ($thumbnail as $value){
                    $m_arr[]   = mb_substr($value['m'],strlen($baseUrl_m));
                    $s_arr[] = mb_substr($value['s'],strlen($baseUrl_s));
                }
                $thumbnail_m = implode(',', $m_arr);
                $thumbnail_s = implode(',', $s_arr);
                break;
            case 'font':
                $baseUrl = "http://d.fenfenriji.com/diary/font/".$goods_info['id']."/priview/";
                $url = array();
                $thumbnails = explode(',', $thumbnail);
                foreach($thumbnails as $value){
                    $url[] = mb_substr($value,strlen($baseUrl));
                }
                $thumbnail_s = $thumbnail_m = implode(',',$url);
                break;
            case 'appskin':
                $baseUrl = "http://d.fenfenriji.com/diary/appskin/".$goods_info['id']."/priview/";
                $url = array();
                $thumbnails = explode(',', $thumbnail);
                
                foreach($thumbnails as $value){
                    $url[] = mb_substr($value,strlen($baseUrl));
                }
                $thumbnail_s = $thumbnail_m = implode(',',$url);
                break;
        }
        
        return array('m' => $thumbnail_m, 's' => $thumbnail_s);
    }
    
    // 组装预览图的修改数据
    private function thumbailImportData ($action, $thumbnail_m, $thumbnail_s = '') {
        $thumbs = array();
        switch ($action) {
            case in_array($action, array('editPaper', 'addPaper', 'editSkin', 'addSkin', 'editFont', 'addFont')):
                if (!empty($thumbnail_m)) {
                    $thumbs = explode(',', trim($thumbnail_m));
                }
                break;
            case in_array($action, array('editEmotion', 'addEmotion')):
                if (!empty($thumbnail_m) && !empty($thumbnail_s)){
                    // 处理预览图
                    $thumbs_m = explode(',', trim($thumbnail_m));
                    $thumbs_s = explode(',', trim($thumbnail_s));
                    for ($i = 0;$i < count($thumbs_m) ; $i ++){
                        $tmp = array(
                                's'    =>    $thumbs_s[$i],
                                'm'    =>    $thumbs_m[$i]
                        );
                        $thumbs[] = $tmp;
                    }
                }
                break;
        }
        
        if (empty($thumbs)) return '';
        
        return json_encode($thumbs);
    }
    
    private function taskImportData () {
        $taskArr = array();
        $task=$_GET['task'];
        isset($_GET['task_type']) && $task=$_GET['task_type']."|".$_GET['task_num'].'|'.$_GET['task_msg'];
        if (!empty($task)) {
            $taskarray = explode('|', $task);
            $taskArr = array(
                'type'    =>    $taskarray[0],
                'num'     =>    $taskarray[1],
                'desc'    =>    $taskarray[2]
            );
        }
     
        if (empty($taskArr)) return '';
      
       return JsonFormat($taskArr);
    }
    
    // 解析下载包链接的地址
    private function parseDownLoadUrl ($download_url) {
        $parts = parse_url($download_url);
        
        $path  = trim($parts['path'], '/');
        $path_arr = explode('/', $path);
    
        if (empty($path_arr)) return array();
        
        $goods_type = $path_arr[1];
        $goods_id   = $path_arr[2];
        $goods_name = substr($path_arr[3], 0, strpos($path_arr[3], '_'));
        
        return array('type' => $goods_type, 'id' => $goods_id, 'name' => $goods_name);
    }
    
    // 样式显示相关变量返回
    private function styleVariable ($action) {
        // 通用变量,样式的显示
        $common = $this->apiAndTplName($action);
    
        $result = array(
            'active'        => array($common['goods'] => " class=\"active\""),         // 侧边栏被选择的样式
            'goods'         => ucfirst($common['goods']),   // 商品名
            'goods_name'    => $common['goods_name'],        // 商品名(中文显示)
        
        );
    
        return $result;
    }
    
    // 样式被选定显示
    private function cssShowActive ($attribute) {
        return array($attribute => " class = \" active\"");
    }
    
    // 样式被选定显示
    private function cssShowSelected ($attribute) {
        return array($attribute => " selected");
    }
    
    
    // 处理返回的数据，返回模板渲染用的数据
    private function resultListData ($result) {
        if (empty($result)) return array();
    
        // 处理返回数据
        foreach ($this->list_name as $tpl) {
            if (!empty($result[$tpl])) {
                return $result[$tpl];
            }
        }
    
        return array();
    }
    
    // 组装返回模板及其他需要的变量
    private function apiAndTplName ($action) {
        if (empty($action)) return array();
    
        // 转小写
        $action = strtolower($action);

        // 返回模板名
        foreach ($this->tpls as $good => $name) {
            if (strpos($action, $good)) {
                if ($this->type == 'vip') {
                   
                    return array('goods' => $good, 'goods_name' => $this->tpls ['pro'.$good]);
                }
                return array('goods' => $good, 'goods_name' => $name);
            }
        }
    
        return array();
    }

    // 返回通用字段
    private function assembleReplacedFieldData ($import, $key_arr = array()) {
        if (empty($key_arr)) {
            return $import;
        }
    
        $result = array();
        foreach ($key_arr as $val) {
            if (isset($import[$val])) {
                $result[$val] = strval($import[$val]);
            }
        }
    
        return $result;
    }
    
    // 获取请求方法
    private function getDo ($action) {
        $do = '';
        switch ($action) {
            case in_array($action, $this->apis['list']) :
                $do = 'getShopList';
                break;
            case in_array($action, $this->apis['detail']) :
                $do = 'getShopDetail';
                break;
            case in_array($action, $this->apis['add']) :
                $do = 'addShop';
                break;
            case in_array($action, $this->apis['edit']) :
                $do = 'editShop';
                break;
            case in_array($action, $this->apis['buy']) :
                $do = 'buyShop';
                break;           
        }
                            
        return $do;  
    }
    
    // 请求api
    private function requestApi ($action, $param) {
        // 实例化
        $param['action'] = $action;
        
        $result=get_api_content($_SC ['apiurl'], $param);
      
        $result=json_decode($result,TRUE);
        $result=$result['resultData'];
        // 请求管理接口返回数据
      
        return $result;
    }
    
    // 模板渲染
    private function render ($tpl, $data=array()) {
       
        // 从数组中把变量导入到当前的符号表中
        extract($data, EXTR_SKIP);
        
        
        
        // 开始输出缓冲, 这时PHP停止输出, 在这以后的输出都被转到一个内部的缓冲里.
        ob_start();
        
        try {
            // 加载本地模板
            include template('admin/'.$tpl);
        } catch (Exception $e) {
            // 删除输出缓冲区
            ob_end_clean();
        
            // 抛出异常
            throw $e;
        }
        
        // 结束输出缓冲, 并扔掉缓冲里的内容.
        return ob_get_clean();
    }
}




$id       = 0;
$type     = 'all';
$uid      = $_SESSION['user']['adminUid'];
$action   = 'getPaperList';
if ($_GET['id'])   $id     = intval($_GET['id']);
if ($_GET['op'])   $action = strval($_GET['op']);
if ($_GET['type']) $type = strval($_GET['type']);


// 初始化
$data = new Data($uid, $type,$id);

echo $data->execute($action);
exit;